package com.bnz.gateway.pred;

import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 功能：定义年龄的断言处理类
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

	public AgeRoutePredicateFactory() {
		super(AgeRoutePredicateFactory.Config.class);
	}
	//1. 定义字段的顺序
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge","maxAge");
	}

	/**
	 * 2. 编写自定义的断言处理逻辑
	 * @param config
	 * @return
	 */
	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return new Predicate<ServerWebExchange>() {
			@Override
			public boolean test(ServerWebExchange exchange) {
				//1. 获取用户输入的年龄参数
				String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
				//2. 如果有年龄参数，再判断范围是否有效
				if(StringUtils.isNotBlank(ageStr)){
					int age = new Integer(ageStr);
					return age >= config.getMinAge() && age <= config.getMaxAge();
				}
				return false;
			}
		};
	}

	@Data
	static class Config{
		private int minAge;
		private int maxAge;
	}
}